<template>
  <div>
    <a-page-header title="角色详情">
      <template #extra>
        <a-button @click="initData" type="primary">刷新</a-button>
        <a-button @click="update" type="primary">修改</a-button>
      </template>
    </a-page-header>
    <div>
      <a-form
        style="width: 60%"
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        v-if="formData.name"
      >
        <a-form-item label="角色名称">
          <a-input readonly v-model:value="formData.name" />
        </a-form-item>
        <a-form-item label="开放注册">
          <a-input readonly v-model:value="formData.allowRegister" />
        </a-form-item>
        <a-form-item label="访问后台视图">
          <a-input readonly v-model:value="formData.isAdminRole" />
        </a-form-item>
        <a-form-item label="允许使用代理">
          <a-input readonly v-model:value="formData.allowUseAgency" />
        </a-form-item>
        <a-form-item v-if="role.allowUseAgency" label="允许使用代理服务">
          <a-input readonly v-model:value="formData.agencyConfIds" />
        </a-form-item>
        <a-form-item label="角色标识符">
          <a-input readonly v-model:value="formData.tag" />
        </a-form-item>
        <a-form-item label="权限级别">
          <a-input readonly v-model:value="formData.level" />
        </a-form-item>
        <a-form-item label="服务角色标识">
          <a-input readonly v-model:value="formData.serviceRoleTag" />
        </a-form-item>
        <a-form-item label="角色权限">
          <a-tree
            :fieldNames="{ children: 'children', title: 'name', key: 'id' }"
            :defaultExpandAll="true"
            :checkable="true"
            :multiple="true"
            :checkedKeys="formData.apis"
            :tree-data="apiTree"
            readonly
          />
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { useI18n } from '@/hooks/useI18n'
  import { useFormModal } from '@/hooks/useModal/useFormModal'
  import type { FormSchema } from '@/components/core/schema-form/src/types/form'
  import {
    updateRole,
    getRole,
    getRoleTags,
    getAllApi,
    getAllService,
    getAgencyConf,
    verifyApis,
  } from '@/api/middleSystem'
  import { ref } from 'vue'
  import { useRoute } from 'vue-router'
  import { formatTreeApi } from '@/utils/filters'
  import { funcB } from './index.vue'
  defineOptions({
    name: 'RoleDetail',
  })

  funcB()

  const route = useRoute()
  // 支持用户管理的服务(修改)
  const currentService = ref<any>([])
  const supportUserInfoManageService = ref<any>([])
  // 服务角色标识(修改)
  const roleTags = ref<any>([])
  const roleOptions = ref<any>([])

  // 当前角色详细信息
  const role = ref<any>()
  // 权限控制组件数据源
  const apiTree = ref<any>([])
  // 详情表单展示字段
  const formData = ref<any>({})
  const loading = ref(false)
  const initData = async () => {
    loading.value = true
    role.value = await getRole(route.params.id as string)
    /* start 获取服务角色相关数据 */
    const serviceRoleTag = await getRoleTags(role.value.id).then((r: any) => {
      let tags = Object.keys(r)
      role.value.num = tags.length
      let str = ''
      currentService.value = []
      roleTags.value = []
      tags.forEach(tag => {
        currentService.value.push(tag)
        roleTags.value.push(Object.keys(r[tag])[0])
        if (!str) str += tag + '(' + Object.keys(r[tag])[0] + ')'
        else str += ',' + tag + '(' + Object.keys(r[tag])[0] + ')'
      })
      return str
    })

    supportUserInfoManageService.value = []
    roleOptions.value = []
    let services: any = (await getAllService(1, 100000, '', true)).data
    services.forEach(service => {
      supportUserInfoManageService.value.push({
        value: service.appId,
      })
      const userRoleTags = Object.keys(service.userRoleTags)
      const tempTags: any[] = []
      userRoleTags.forEach(tag => {
        tempTags.push({
          value: tag,
        })
      })
      roleOptions.value.push(tempTags)
    })
    /* end 获取服务角色相关数据 */

    /* start 获取权限分配数据 */
    const { data: apiData } = await getAllApi()
    const apiList = apiData
    const temporaryTree = formatTreeApi(apiData)
    const { data: serviceData } = await getAllService(1, 100000, '')
    serviceData.push({ appId: 'middleSystem', name: '中台服务', children: [] })
    serviceData.forEach((item: any) => {
      item.id = item.appId ? item.appId : 'middleSystem'
      item.children = []
      temporaryTree.forEach((value: any) => {
        if (item.appId == value.children[0].appId) item.children.push(value)
        if (!value.children[0].appId && item.id == 'middleSystem') item.children.push(value)
      })
    })
    apiTree.value = serviceData
    /* end 获取权限分配数据 */

    /* start 详情表单展示 */
    formData.value.name = role.value.name
    formData.value.allowRegister = role.value.allowRegister ? '是' : '否'
    formData.value.isAdminRole = role.value.isAdminRole ? '是' : '否'
    formData.value.allowUseAgency = role.value.allowUseAgency ? '是' : '否'
    if (role.value.allowUseAgency) {
      formData.value.agencyConfIds = role.value.agencyConfIds
        .map((item: any) => {
          return item.name
        })
        .join(',')
    }
    formData.value.tag = role.value.tag
    formData.value.level = role.value.level
    formData.value.serviceRoleTag = serviceRoleTag
    formData.value.apis = []
    apiList.forEach((i: any) => {
      role.value.api.forEach((o: any) => {
        if (i.url === o.url && i.method === o.method) {
          formData.value.apis.push(i.id)
        }
      })
    })
    /* end 详情表单展示 */

    loading.value = false
  }
  initData()

  // todo
  let updateformRef: any
  const changeNum = value => {
    console.log(value)
  }

  const { t } = useI18n()
  const [showModal] = useFormModal()
  const formSchemas: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      label: '角色名称',
      rules: [{ required: true }],
    },
    {
      field: 'tag',
      component: 'Input',
      label: '标识符',
      rules: [{ required: true }],
    },
    {
      field: 'level',
      component: 'Input',
      label: '权限级别',
      rules: [{ required: true }],
    },
    {
      field: 'num',
      component: 'InputNumber',
      label: '服务角色',
      componentProps: {
        min: 0,
        onChange: changeNum,
      },
      rules: [{ required: true }],
    },
    // {
    //   field: 'name',
    //   component: 'Input',
    //   label: '支持用户管理的服务',
    //   rules: [{ required: true }],
    // },
    // {
    //   field: 'name',
    //   component: 'Input',
    //   label: '服务角色标识',
    //   rules: [{ required: true }],
    // },
    {
      field: 'allowRegister',
      component: 'Switch',
      label: '开放注册',
      defaultValue: false,
    },
    {
      field: 'isAdminRole',
      component: 'Switch',
      label: '访问后台视图',
      defaultValue: false,
    },
    {
      field: 'allowUseAgency',
      component: 'Switch',
      label: '允许使用代理',
      defaultValue: false,
    },
    {
      field: 'agencyConfIds',
      component: 'Select',
      label: '允许代理服务',
      vIf: ({ formModel }) => formModel['allowUseAgency'] == true,
      componentProps: {
        mode: 'multiple',
        showSearch: true,
        optionFilterProp: 'label',
        request: async () => {
          return (await getAgencyConf.request({ pageSize: 100000 })).data.map((item: any) => {
            return { label: item.name, value: item.id }
          })
        },
      },
    },
    {
      field: 'apis',
      component: 'Tree',
      label: '权限分配',
      componentProps: {
        defaultExpandAll: true,
        checkable: true,
        multiple: true,
        vModelKey: 'checkedKeys',
        fieldNames: { children: 'children', title: 'name', key: 'id' },
      },
    },
  ]

  function extractItemsByIds(tree, ids) {
    let result: any = []
    function traverse(node) {
      if (ids.includes(node.id) && !node.children) {
        result.push(node)
      }
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => traverse(child))
      }
    }
    tree.forEach(rootNode => traverse(rootNode))
    return result
  }

  const update = async () => {
    const [formRef] = await showModal({
      modalProps: {
        title: t('common.edit'),
        width: '40%',
        onFinish: async values => {
          let {
            name,
            tag,
            level,
            allowRegister,
            isAdminRole,
            allowUseAgency,
            agencyConfIds,
            apis,
            password,
          } = values
          let filteredItems = apis?.length ? extractItemsByIds(apiTree.value, apis) : []
          let rts: any[] = []
          roleTags.value.forEach((rt, index) => {
            rts.push({
              service: currentService.value[index],
              tag: rt,
            })
          })

          let flag = await verifyApis(filteredItems)

          if (flag && !password) {
            message.warning('您已勾选了敏感权限接口,需要重新输入密码对操作进行确认!')
            formRef?.appendSchemaByField({
              field: 'password',
              component: 'Input',
              label: '密码',
              rules: [{ required: true }],
            })
            throw new Error('您已勾选了敏感权限接口,需要对操作进行确认!')
          }

          await updateRole(
            role.value.id,
            name,
            filteredItems,
            allowRegister,
            isAdminRole,
            allowUseAgency,
            allowUseAgency ? agencyConfIds : [],
            tag,
            +level,
            rts,
            password,
          )
          message.success('操作成功')
          initData()
        },
      },
      formProps: {
        labelWidth: 100,
        layout: 'horizontal',
        schemas: formSchemas,
      },
    })
    updateformRef = formRef
    formRef?.updateSchema([
      {
        field: 'apis',
        componentProps: { treeData: apiTree.value },
      },
    ])
    formRef?.setFieldsValue({
      name: role.value.name,
      tag: role.value.tag,
      level: role.value.level,
      num: role.value.num,
      allowRegister: role.value.allowRegister,
      isAdminRole: role.value.isAdminRole,
      allowUseAgency: role.value.allowUseAgency,
      agencyConfIds: role.value.agencyConfIds.map(item => item._id),
      apis: formData.value.apis,
    })
  }
</script>
<script lang="ts">
  export var funcA = () => {
    console.log('----------------------------a')
  }
</script>
<style lang="scss" scoped>
  .ant-page-header {
    padding: 0 0 24px 0;
  }
  .ant-page-header-heading-title {
    font-size: 16px !important;
  }
</style>
